<template>
  <div id="login">
    <div style="text-align: center">
      <h2>注册</h2>
    </div>
    <a-form
      id="components-form-demo-normal-login"
      :form="form"
      class="login-form"
      @submit="handleSubmit"
    >
      <a-form-item>
        <a-input
          v-decorator="[
            'username',
            { rules: [{ required: true, message: '请输入用户名!' }] },
          ]"
          placeholder="用户名"
        >
          <a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          v-decorator="[
            'password',
            { rules: [{ required: true, message: '请输入密码！' }] },
          ]"
          type="password"
          placeholder="密码"
        >
          <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          v-decorator="[
            'passwordAgain',
            { rules: [{ required: true, message: '请输入密码！' }] },
          ]"
          type="password"
          placeholder="再此输入密码"
        >
          <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" class="login-form-button">
          注册
        </a-button>
        <a href="" @click="goLogin"> 返回登录</a>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
export default {
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
  },
  methods: {
    goLogin(e) {
      e.preventDefault();
      this.$router.push("/login");
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values);
          const { password, passwordAgain, username } = values;
          if (password !== passwordAgain) {
            this.$message.error("两次密码输入不相同");
            return;
          }
          this.$axios.post("/user/register",{...values}).then(res=>{
            this.$message.success("注册成功")
            res.data.error===-1&&this.goLogin(e)
          })
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
#login {
  width: 400px;
  height: 300px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 30px;
  right: 0;
  margin: auto;
  text-align: left;
}
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
</style>
